/**
* Copyright (C) 2018-2020
* All rights reserved, Designed By www.yixiang.co
* 注意：
* 本软件为www.yixiang.co开发研制，未经购买不得使用
* 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
* 一经发现盗用、分享等行为，将追究法律责任，后果自负
*/
package co.yixiang.modules.appdict.service.impl;

import co.yixiang.common.service.impl.BaseServiceImpl;
import co.yixiang.common.utils.QueryHelpPlus;
import co.yixiang.dozer.service.IGenerator;
import co.yixiang.modules.appdict.domain.Appdict;
import co.yixiang.modules.appdict.service.AppdictService;
import co.yixiang.modules.appdict.service.dto.AppdictDto;
import co.yixiang.modules.appdict.service.dto.AppdictQueryCriteria;
import co.yixiang.modules.appdict.service.mapper.AppdictMapper;
import co.yixiang.utils.FileUtil;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

// 默认不使用缓存
//import org.springframework.cache.annotation.CacheConfig;
//import org.springframework.cache.annotation.CacheEvict;
//import org.springframework.cache.annotation.Cacheable;

/**
* @author yhh
* @date 2020-08-07
*/
@Service
@AllArgsConstructor
//@CacheConfig(cacheNames = "appdict")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class AppdictServiceImpl extends BaseServiceImpl<AppdictMapper, Appdict> implements AppdictService {

    private final IGenerator generator;

    @Override
    //@Cacheable
    public Map<String, Object> queryAll(AppdictQueryCriteria criteria, Pageable pageable) {
        getPage(pageable);
        PageInfo<Appdict> page = new PageInfo<>(queryAll(criteria));
        Map<String, Object> map = new LinkedHashMap<>(2);
        map.put("content", generator.convert(page.getList(), AppdictDto.class));
        map.put("totalElements", page.getTotal());
        return map;
    }


    @Override
    //@Cacheable
    public List<Appdict> queryAll(AppdictQueryCriteria criteria){
        return baseMapper.selectList(QueryHelpPlus.getPredicate(Appdict.class, criteria));
    }

    /**
     * 构建树形
     *
     * @param appdictDtos 分类列表
     * @return map
     */
    @Override
    public Map<String, Object> buildTree(List<AppdictDto> appdictDtos) {
        Set<AppdictDto> trees = new LinkedHashSet<>();
        Set<AppdictDto> cates = new LinkedHashSet<>();
        List<String> deptNames = appdictDtos.stream().map(AppdictDto::getName)
                .collect(Collectors.toList());

        //YxStoreCategoryDto categoryDTO = new YxStoreCategoryDto();
        Boolean isChild;
        List<Appdict> categories = this.list();
        for (AppdictDto deptDTO : appdictDtos) {
            isChild = false;
            if ("0".equals(deptDTO.getParentOid())) {
                trees.add(deptDTO);
            }
            for (AppdictDto it : appdictDtos) {
                if (it.getParentOid().equals(deptDTO.getOid())) {
                    isChild = true;
                    if (deptDTO.getChildren() == null) {
                        deptDTO.setChildren(new ArrayList<AppdictDto>());
                    }
                    deptDTO.getChildren().add(it);
                }
            }
            if (isChild)
                cates.add(deptDTO);
            for (Appdict category : categories) {
                if (category.getOid().equals(deptDTO.getParentOid()) && !deptNames.contains(category.getName())) {
                    cates.add(deptDTO);
                }
            }
        }


        if (CollectionUtils.isEmpty(trees)) {
            trees = cates;
        }


        Integer totalElements = appdictDtos != null ? appdictDtos.size() : 0;

        Map<String, Object> map = Maps.newHashMap();
        map.put("totalElements", totalElements);
        map.put("content", CollectionUtils.isEmpty(trees) ? appdictDtos : trees);
        return map;
    }


    @Override
    public void download(List<AppdictDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (AppdictDto appdict : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("字典名称 : 字典名称", appdict.getName());
            map.put("上级字典主键 : 上级字典编号，顶级字典为NULL", appdict.getParentOid());
            map.put("字典项描述 : 该字典项的说明", appdict.getMemo());
            map.put("字典主键路径 : 字典项主键路径，用于查询多级", appdict.getPath());
            map.put("删除状态 : 删除状态", appdict.getIsDelete());
            map.put("创建时间 : 当前字典项的创建时间", appdict.getCreateDate());
            map.put("图片", appdict.getImages());
            map.put("字典菜单类型", appdict.getDictType());
            map.put(" code",  appdict.getCode());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public List<Appdict> findListByCode(String code) {
        return this.baseMapper.findListByCode(code);
    }

    @Override
    public Appdict findOneByCode(String code) {
        return this.baseMapper.findOneByCode(code);
    }
}
